package com.woniuxy.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.config.RabbitMqConfig;
import com.woniuxy.rabbitmq.sender.FirstSender;
import com.woniuxy.service.AuctionService;
import com.woniuxy.util.JsonUtil;
import com.woniuxy.util.SpringUtil;
import com.woniuxy.util.TimeUtil;
import com.work.framework.pojo.Auction;
import com.work.framework.pojo.BiddingRecord;
import com.work.framework.pojo.Chat;
import com.work.framework.pojo.ResultDTO;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

/**
 * @author kyle
 * @date 2019-09-19 16:44
 */
@Api(value = "竞拍室")
@ServerEndpoint("/auction/websocket/{aid}/{uuid}")
@Component
public class AuctionWebSocketHandler {

    @Resource
    private FirstSender firstSender;
    @Resource
    private AuctionService auctionService;
    private static final Map<String, Map<String,Session>> auction_Sessioins = new Hashtable<>();

    @OnOpen
    public void onOpen (Session session, @PathParam(value = "aid") String aid,@PathParam(value = "uuid") String uuid) {
        if (firstSender == null || auctionService == null) {
            firstSender = SpringUtil.getBean(FirstSender.class);
            auctionService = SpringUtil.getBean(AuctionService.class);
        }
        System.out.println("websocket 建立连接成功" + session);
        Map<String, Session> stringSessionMap = auction_Sessioins.get(aid);
        if (stringSessionMap == null) {
            stringSessionMap = new HashMap<>();
        }
        stringSessionMap.put(uuid,session);
        auction_Sessioins.put(aid, stringSessionMap);
        System.out.println("aid"+aid+"auction_Sessioins"+auction_Sessioins+"--"+auction_Sessioins.get(aid+""));
    }

    @OnMessage
    public void onMessage (String message,@PathParam(value = "aid") String aid ) {
        //发送的信息合法性判断
        if (message == null || message.length() == 0) {
            return;
        }
        //解析message数据
        BiddingRecord biddingRecord = JsonUtil.StringToObject(message);
        if (biddingRecord == null) {
            return;
        }
        //设置信息的时间
        biddingRecord.setAuctionTime(TimeUtil.getLocalTime());
        biddingRecord.setStatus(1);
        //验证是否有权限
        ResultDTO resultDTO = auctionService.verifyUserQualification(biddingRecord.getAid(), biddingRecord.getUid());
        if (resultDTO.getCode() == 500) {
            return;
        }
        //通过mq发送信息给后台加入数据库中
        firstSender.send(UUID.randomUUID().toString(),JsonUtil.ObjectToString(biddingRecord), RabbitMqConfig.EXCHANGE_AUCTION,RabbitMqConfig.ROUTINGKEY_AUCTION);
        //推送前端
        Map<String, Session> stringSessionMap = auction_Sessioins.get(aid);
        Set<Map.Entry<String, Session>> entries = stringSessionMap.entrySet();
        for (Map.Entry<String, Session> entry : entries) {
            final RemoteEndpoint.Basic basic = entry.getValue().getBasicRemote();
            if (basic!=null) {
                try {
                    //发送消息回客户端
                    basic.sendText(new ObjectMapper().writeValueAsString(biddingRecord));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @OnError
    public void onError (@PathParam("aid")Integer aid,@PathParam("uuid")String uuid,Session session, Throwable error) {
        System.out.println("websocket异常连接已经关闭"+session+"uuid:"+uuid);
        error.printStackTrace();
        Map<String, Session> stringSessionMap = auction_Sessioins.get(aid+"");
        if (stringSessionMap != null) {
            stringSessionMap.remove(uuid);
        }
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose (@PathParam("uuid")String uuid,@PathParam("aid")Integer aid,Session
            session) {
        System.out.println("websocket连接已经关闭"+session+"uuid:"+uuid);
        Map<String, Session> stringSessionMap = auction_Sessioins.get(aid+"");
        if (stringSessionMap != null) {
            stringSessionMap.remove(uuid);
        }
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
